import { useApprovalDesignerStore } from '@/store/modules/dsgn/ApprovalDesigner'
import { FieldPermissionType } from '@/components/SimpleProcessDesignerV2/src/consts'
import { cloneDeep } from 'lodash-es'

const designerStore = useApprovalDesignerStore()

/**
 * @description 表单数据权限配置，用于发起人节点 、审批节点、抄送节点
 */
export function useApprovalFormFieldsPermission(defaultPermission: FieldPermissionType) {
  // 字段权限配置. 需要有 field, title,  permissioin 属性
  const fieldsPermissionConfig = ref<Array<Record<string, string>>>([])

  const formType = inject<Ref<number>>('formType') // 表单类型

  // const formFields = inject<Ref<string[]>>('formFields') // 流程表单字段

  const formFields = designerStore.designerModel.form.configJson.widgetList
  const getNodeConfigFormFields = (nodeFormFields?: Array<Record<any, any>>) => {
    nodeFormFields = toRaw(nodeFormFields)
    fieldsPermissionConfig.value =
      cloneDeep(nodeFormFields) || getDefaultFieldsPermission(unref(formFields))
  }
  // 默认的表单权限： 获取表单的所有字段，设置字段默认权限为只读
  const getDefaultFieldsPermission = (formFields?: any[]) => {
    const defaultFieldsPermission: Array<Record<string, string>> = []
    if (formFields) {
      formFields.forEach((fieldStr: any) => {
        parseFieldsSetDefaultPermission(fieldStr, defaultFieldsPermission)
      })
    }
    return defaultFieldsPermission
  }
  // 解析字段。赋给默认权限
  const parseFieldsSetDefaultPermission = (
    rule: Record<string, any>,
    fieldsPermission: Array<Record<string, string>>,
    parentTitle: string = ''
  ) => {
    const { /**type,*/ field, title: tempTitle, children } = rule
    if (field && tempTitle) {
      let title = tempTitle
      if (parentTitle) {
        title = `${parentTitle}.${tempTitle}`
      }
      fieldsPermission.push({
        field,
        title,
        permission: defaultPermission
      })
      // TODO 子表单 需要处理子表单字段
      // if (type === 'group' && rule.props?.rule && Array.isArray(rule.props.rule)) {
      //   // 解析子表单的字段
      //   rule.props.rule.forEach((item) => {
      //     parseFieldsSetDefaultPermission(item, fieldsPermission, title)
      //   })
      // }
    }
    if (children && Array.isArray(children)) {
      children.forEach((rule) => {
        parseFieldsSetDefaultPermission(rule, fieldsPermission)
      })
    }
  }

  return {
    formType,
    fieldsPermissionConfig,
    getNodeConfigFormFields
  }
}
